package com.demo.eshop.pdetail.request;

import com.demo.eshop.pdetail.entity.ProductInventory;
import com.demo.eshop.pdetail.service.product.ProductInventoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: e20160504
 * @date: 2018/10/29
 * @desc  比如说一个商品发生了交易，那么就要修改这个商品对应的库存
 *
 * cache aside pattern
 * 1.删除缓存
 * 2.更新数据库
 */
public class ProductInventoryUpdateRequest implements Request {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private ProductInventory productInventory;
    private ProductInventoryService productInventoryService;

    public ProductInventoryUpdateRequest(ProductInventory productInventory, ProductInventoryService productInventoryService) {
        this.productInventory = productInventory;
        this.productInventoryService = productInventoryService;
    }

    @Override
    public void process() {

        logger.info("====库存更新请求开始执行，商品Id = {}，商品库存 = {}", productInventory.getProductId(),productInventory.getInventoryCnt());

        // 删除redis缓存
        productInventoryService.removeProductInventoryCache(productInventory);

        //// 为了模拟演示先删除了redis中的缓存，然后还没更新数据库的时候，读请求就过来了，这里可以人工sleep一下
        //try {
        //    Thread.sleep(5000);
        //} catch (InterruptedException e) {
        //    e.printStackTrace();
        //}

        // 更新数据库
        productInventoryService.updateProductInventory(productInventory);
    }

    @Override
    public Integer getProductId() {
        return productInventory.getProductId();
    }

    @Override
    public boolean isForceRefresh() {
        return false;
    }


}
